extends Node2D

const ENEMY = preload("res://scenes/enemy.tscn")

# 各角色的属性
var enemies = [Characters.FlameImp,Characters.SeaMage,Characters.YoungWyrm,Characters.Somnia,Characters.DemonSoldier]
var allies = [Characters.Mage,Characters.Gladiator,Characters.YoungWyrm,Characters.RoyalGuard,Characters.ShieldWarrior]
# 保存创建的各个角色
var enemies_obj = []
var allies_obj = []
var battle_list:Array = []
var cur_character
var cur_index:int = 0
var cur_round: int = 1 :
	set(value):
		cur_round = value
		%round.text = "第"+str(value)+"回合"
	get:
		return cur_round

func initGame():
	initPos(enemies,%left_markers,false)
	initPos(allies,%right_markers,true)
	
func initPos(_list,_markers_group,_flip):
	var list_length = _list.size()
	if list_length>5:
		list_length = 5
	for index in range(list_length):
		var ally = ENEMY.instantiate()
		ally.texture_path = _list[index].texture
		ally.init(_list[index])
		if _flip:
			ally.animate_sprite.flip_h = true
			ally.group = "allies"
			allies_obj.append(ally)
		else:
			print('add to enemies')
			print(ally)
			ally.group = "enemies"
			enemies_obj.append(ally)
		ally.global_position = _markers_group.get_child(index).global_position
		add_child(ally)
		ally.action_finished.connect(on_action_finished)
		ally.character_die.connect(on_character_die)
	pass

func battle():
	set_battle_list()

func start_battle():
	print("start_battle")
	if allies_obj.size() <= 0 or enemies_obj.size() <= 0:
		over()
		return
	cur_character = battle_list[cur_index]
	var target_list = allies_obj
	if cur_character.group == "allies":
		target_list = enemies_obj
	var target = target_list[randi_range(0,target_list.size()-1)]
	cur_character.start_attack(target)
	pass
func next_one():
	print("next")
	cur_index += 1
	if cur_index >= battle_list.size():
		next_round()
	else:
		start_battle()
	pass
	
func set_battle_list():
	battle_list = allies_obj.duplicate()
	battle_list.append_array(enemies_obj)
	battle_list.sort_custom(func (a,b):	
		return a.attributes.attributes.speed > b.attributes.attributes.speed
	)
	start_battle()
	
func next_round():
	cur_round += 1
	cur_index = 0
	battle()
	
func over():
	var result_text = "失败！"
	if enemies_obj.size() <= 0:
		result_text = "胜利！"
		for item in allies_obj:
			item.animate_sprite.play("win")
	%result_label.text = result_text
	%result_label.show()
	%round.hide()

func on_action_finished():
	next_one()
	
func on_character_die(obj):
	battle_list.erase(obj)
	allies_obj.erase(obj)
	enemies_obj.erase(obj)
	obj.queue_free()
# Called when the node enters the scene tree for the first time.
func _ready():
	initGame()
	pass # Replace with function body.

func _on_start_battle_button_pressed() -> void:
	battle()
	pass # Replace with function body.
